#include "stats.h"
#include <stdio.h>
#include <stdlib.h>

void print_stats (Digraph H, int iterations, double time, double parameter,
    double epsilon, const char *label, const char *par_name)
{
  printf("---------------------------------------\n");
  printf("      Algorithm used: %s\n", label);
  printf("Digraph size  (V, A): %7d | %7d\n", H->V, H->A);
  printf(  "%5s arg. & epsilon: %7.5f | %.1e\n", par_name, parameter, epsilon);
  printf("Number of iterations: %d\n", iterations);
  printf("        Time elapsed: %.3fs\n", time);
  printf("---------------------------------------\n");
}

void print_vector (double *x, int n, const char *label)
{
  int i;

  printf("%s = (", label);
  for (i = 0; i < n; i++) printf("%.4f ", x[i]);
  printf("%c)\n\n", 8);
}

void print_vector_i (int *x, int n, const char *label)
{
  int i;

  printf("%s = (", label);
  for (i = 0; i < n; i++) printf("%d ", x[i]);
  printf("%c)\n\n", 8);
}


int *find_top_values (double *pi, int size, int num)
{
  int *index;
  int i, j, k;

  index = malloc(num * sizeof(int));

  for (i = 0; i < num; i++) index[i] = -1;

  for (i = 0; i < size; i++) {
    for (j = 0; j < num; j++) {
      if (index[j] == -1) {
        index[j] = i;
        break;
      }
      else {
        if (pi[i] > pi[index[j]]) {
          for (k = num - 1; k > j; k--) {
            index[k] = index[k - 1];
          }
          index[j] = i;
          break;
        }
      }
    }
  }
  return index;
}

int same_index (int *a, int *b, int size, int top, int *max_dist, int *pos)
{
  int i, ans, dist;
  double sum;
  ans = 0;

  printf("Regarding the top %d pages.\n", top);
  if (top > size) top = size;
  sum = 0;
  printf("-------------------------------------\n");
  printf("| Index | Pos @ 1 | Pos @ 2 | diff  |\n");
  printf("-------------------------------------\n");
  for (i = 0; i < top; i++) {
    dist = distance(a[i], a, b, size);
    if (dist == 0) ans++;
    else {
      sum += abs(dist);
      if (abs(dist) > abs(*max_dist)) {
        *max_dist = dist;
        *pos = i;
      }
    }
    printf("| %5d | %7d | %7d | %5d |\n", a[i], i, i + dist, dist);
  }
  printf("------------------------------------\n");
  if (top - ans != 0) printf("Avg. distance: %.3f\n", sum / (top - ans));
  else printf("Avg. distance: 0\n");

  return ans;
}

int distance (int page, int *a, int *b, int size)
{
  int i, pos1, pos2, dist;
  pos1 = pos2 = -1;
  for (i = 0; i < size; i++) {
    if (a[i] == page) pos1 = i;
    if (b[i] == page) pos2 = i;
  }
  if (pos1 < 0 || pos2 < 0) printf("WARNING!\n");
  dist = pos2 - pos1;
  return dist;
}

